package com.task.manager.job;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.task.manager.annotation.TaskJob;
import com.task.manager.config.quartz.AbstractJob;
import com.task.manager.domain.Task;
import com.task.manager.domain.TaskResult;
import com.task.manager.enums.ActuatorMethod;
import com.task.manager.enums.ActuatorProtocol;
import com.task.manager.enums.ActuatorType;
import com.task.manager.enums.TaskType;
import com.task.manager.util.GsonUtil;
import com.task.manager.util.HttpClientUtil;

@TaskJob(actuatorCode="httpGetJob",actuatorName="http的get请求Job", actuatorMethod = ActuatorMethod.GET, actuatorProtocol = ActuatorProtocol.HTTP, actuatorClass = "com.task.manager.job.HttpGetJob")
@Component
public class HttpGetJob extends AbstractJob {
	
	private static Logger log = LoggerFactory.getLogger(HttpGetJob.class);
	
	@Autowired
	private HttpClientUtil httpClientUtil;
	
	@Override
	public void executeWithLock(Task task,TaskResult taskResult,TaskType taskType){
		try {
			String url = task.getTaskUrl();
			@SuppressWarnings("unchecked")
			Map<String,String> header = GsonUtil.jsonToObject(task.getTaskHeader(), Map.class);
			if(TaskType.ASYNC.equals(taskType)) {
				header.put("resultId", taskResult.getId()+"");
			}
			String resStr = httpClientUtil.doGet(url, header);
			taskResult.setActuatorType(ActuatorType.TASK_PACKAGE.name());
			taskResult.setInput("{url:"+url+",header:"+header+"}");
			taskResult.setOutput(resStr);
			taskResult.setResult(true);
			if(TaskType.ASYNC.equals(taskType)) {
				taskResult.setResult(null);
			}
		} catch (Exception e) {
			log.error("执行"+task.getTaskName()+"任务,"+task.getTaskCode()+"代码失败,失败原因"+e.getMessage(),e);
			taskResult.setResult(false);
			taskResult.setException(e.getMessage());
		}
	}
}
